﻿<?php
/**
 * Script used to create a new folder
 */
header ('Content-type: application/json');

session_start();
require_once '../core/db.php';

if (!isset($_SESSION['user']))		// No filesystem write operations if not logged in
	die (json_encode (array ('error'=>'No user logged on')));
	
// If no parentid, then set parentid=-1, ie. the root folder
if ($_POST['parentId']=='undefined')
	$_POST['parentId'] = -1;

// Insert a new folder item into the folders table, the parentid is the id of the 
// parent folder.
$sql = 'INSERT INTO folder (user, name, parent) VALUES (?, ?, ?)';
$sth = $db->prepare ($sql);
// Send the statement to the database, create the new folder
$res = $sth->execute (array ($_SESSION['user'], $_POST['name'], $_POST['parentId']));
if ($res==0)	// No folder created, send an error message
	die (json_encode (array ('error'=>'Error during database operation')));
	
// Return the content of the parent folder where this folder was created
$sql = 'SELECT name, id, user FROM folder WHERE user=? and parent=? order by name';
$sth = $db->prepare ($sql);
$sth->execute (array ($_SESSION['user'], $_POST['parentId']));
// Get all the results, json encode and return
die (json_encode  ($sth->fetchAll ()));
?>